/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 *
 * @format
 * @flow
 */

import React, {Component} from 'react';
import {Platform,StatusBar,NetInfo,StyleSheet,Alert, TouchableOpacity,TextInput,Text,Image,Button,View} from 'react-native';
import { NavigationActions,StackActions } from 'react-navigation';
// import mainPage from "./src/page/mainPage"
// import registerPage from './src/page/register'
// import forgetPassPage from './src/page/forgetPassWord'
// import peelPage from './src/page/peel'
// import checkPage from './src/page/check'
// import qrPage from './src/component/qrScanner'
// import bloodPage from './src/page/blood'
// import ovuPage from './src/page/ovulation'
// import pregPage from './src/page/pregnant'
// import checkPeelResultPage from './src/page/checkPeelResult'
import {SERVER} from './src/util/config'
import NET from './src/util/netUtil'
import Toast from 'react-native-root-toast'; 
import { Initializer } from 'react-native-baidumap-sdk'
import {connect} from 'react-redux'

import {setNetStatus} from './src/Actions/checkNetAction'
//import {Navi} from './src/Router/pageRouter'


Initializer.init('ymhzfCdDEbSyRTV2jaa8sncLfQ5nWP74')



var navigation = null;

class App extends Component {
  
  constructor(props){
    super(props);
    this.state={
      NetWorkOK:false,
      name:"",
      code:""
    }
    navigation = this.props.navigation;
    this._login=this._login.bind(this);
    this._forgetPass=this._forgetPass.bind(this);
    this._register=this._register.bind(this);
    this._QQ=this._QQ.bind(this);
    this._weChat=this._weChat.bind(this);
    this.handleConnectivityChange=this.handleConnectivityChange.bind(this);
    // this.NetWorkOK=false;

    

}


  static navigationOptions = {
    header: null,
    cardStack: {
      gesturesEnabled: false  // 是否可以右滑返回
  }
};

//WARNING! To be deprecated in React v17. Use componentDidMount instead.
componentWillMount() {
  NetInfo.isConnected.fetch().done((isConnected) => {
    //this.setState({NetWorkOK:isConnected})
    this.props.dispatch(setNetStatus(isConnected));//传递到redux系统中，供全局使用

    // console.log('First, is ' + (isConnected ? 'online' : 'offline'));
  });

  NetInfo.addEventListener('connectionChange', this.handleConnectivityChange);


}

componentWillUnMount() {
  console.log("componentWillUnMount");
  NetInfo.removeEventListener('connectionChange', this.handleConnectivityChange);
}

handleConnectivityChange(status) {

//Toast.show(JSON.stringify(status));
  NetInfo.isConnected.fetch().done((isConnected) => {
   //this.NetWorkOK=isConnected;
   //this.setState({NetWorkOK:isConnected})

   this.props.dispatch(setNetStatus(isConnected));//传递到redux系统中，供全局使用
    Toast.show('当前网络状态：' + (isConnected ? '网络正常' : '无网络'));
   // console.log('First, is ' + (isConnected ? 'online' : 'offline'));
  });
}


_login(){

  if(this.state.name!=""&&this.state.code!="")
  {

        if(this.props.Net.NetWorkOK){

                let data={"username":this.state.name,"pass":this.state.code}
              let url=SERVER+"/users/login";
            // Alert.alert(JSON.stringify(data));
              NET.post(url,data,(res)=>{
              // Alert.alert(JSON.stringify(res));

              if(res.status=='100') 
              {

              //  this.props.dispatch(NavigationActions.navigate({routeName:'main'}));//
               // this.props.dispatch(StackActions.replace({routeName:'main'}));
                  navigation.replace('main');

                // Navi.router.replace('main')
                console.log(this.props);
              }else
              {
                Alert.alert("账户名密码错误！");
              }

              });

        }else{
          Toast.show("当前无网络连接，请连接网络!")
        }
        

  }else
  {
    Alert.alert('用户名、密码不能为空！');
  }
  
}
_forgetPass(){

  //navigation.navigate('main');

  
}
_register(){

  //navigation.navigate('main');
  Toast.show("内测版,请向运营人员索取体验账号");
  
}

_QQ(){

  Toast.show("暂未开放");

  
}

_weChat(){
  Toast.show("暂未开放");
  //navigation.navigate('main');
 
}


  render() {

    
     // this.props.dispatch(setNetStatus(0));//传递到redux系统中，供全局使用

   // const { navigate } = this.props.navigation;


    return (
      <View style={styles.container}>
        <StatusBar  
             animated={true} //指定状态栏的变化是否应以动画形式呈现。目前支持这几种样式：backgroundColor, barStyle和hidden  
             hidden={true}  //是否隐藏状态栏。  
              // backgroundColor={'green'} //状态栏的背景色  
              // translucent={true}//指定状态栏是否透明。设置为true时，应用会在状态栏之下绘制（即所谓“沉浸式”——被状态栏遮住一部分）。常和带有半透明背景色的状态栏搭配使用。  
             barStyle={'light-content'} // enum('default', 'light-content', 'dark-content')   
                        >  
         </StatusBar>  

        <View style={styles.first}>
           <TouchableOpacity style={[styles.sharebtn,styles.center]} onPress={this._register}>
             <Text style={styles.zhuce}>注册</Text>
           </TouchableOpacity >
        </View>

        <View style={styles.second}>
            <Image 
              style={styles.img}
             source={require('./res/images/logo.png')}
            ></Image>
            <TextInput
            style={[styles.user,styles.baseInput]}
            placeholder="请输入手机号"
            underlineColorAndroid="transparent"
            keyboardType="numeric"
            clearButtonMode="always"
            clearTextOnFocus={true}
            autoCapitalize='none'
            placeholderStyle={{paddingLeft: 10}}
            onChangeText={(text) => {
              const newText = text.replace(/[^\d]+/, '');
              this.setState({name: newText})
            }}
            ></TextInput>

            <TextInput   
              style={[styles.baseInput,styles.code]}        
              placeholder="请输入密码(至少8个字符)"
              placeholderStyle={{paddingLeft: 10}}
              password={true}
              underlineColorAndroid="transparent"
              onChangeText={(text) => {
                this.setState({code:text})
              }}
              secureTextEntry={true}

            ></TextInput>
           <TouchableOpacity style={[styles.center]} onPress={this._forgetPass}>
               <Text style={styles.forgetcode}>忘记密码？</Text>
           </TouchableOpacity>

            <TouchableOpacity style={[styles.btn,styles.center]} onPress={this._login}>
                <Text style={styles.font}
                > 登录</Text>
            </TouchableOpacity>         
        </View>


        <View style={styles.third}>
          <Text style={styles.fengexian}>━━━━━    第三方登录    ━━━━━</Text>
          <View style={[styles.share,styles.center]}>
               <TouchableOpacity style={[styles.center]} onPress={this._QQ}>
                   <View style={styles.weixin}>
                      <Image style={styles.qq1} source={require('./res/images/icon_qq.png')}></Image>
                   </View>
                   <Text style={styles.font2}>QQ</Text>
               </TouchableOpacity>
               <Text>      </Text>
               <TouchableOpacity style={[styles.center]} onPress={this._weChat}>
                  <View style={styles.weixin}>
                      <Image style={styles.qq2}  source={require('./res/images/icon_weixin.png')}></Image>
                   </View>
                   <Text style={styles.font2}>微信</Text>
               </TouchableOpacity>
          </View>
        </View>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,  
    backgroundColor: 'rgb(69,122,173)',
  },
  center:{
    alignItems:'center',
    justifyContent: 'center',
  },
  baseInput:{
    backgroundColor: '#fff',
    height:45,
    borderRadius:3,
    //width:width,
    marginLeft:50,
    marginRight:50,
   
    padding: 0,
   
  },
  first: {
    top:Platform.OS==='ios'?20:0,
    alignSelf: 'flex-end',
    //flex:,
  },
  second: {
    flex:4,
    
  },
  third: {
    flex:2,
  },
  zhuce:{
    color:'#FFFFFF',
    fontSize:15,
    marginRight: 20,
    marginTop: 20,

  },
  img:{
    resizeMode:'contain',
    alignSelf: 'center',
    width:100,
    height:100,
    marginTop: 50,
   
    // elevation: 20,
    // shadowOffset: {width: 4, height: 4},
    // shadowColor: 'white',
    // shadowOpacity: 1,
    // shadowRadius: 10


  },
  user:{ 
    marginTop: 40,
  },
  code:{
    marginTop:20,
   },
  forgetcode:{ 
    fontSize:10,
    color:"#FFFFFF",
    alignSelf: 'flex-end',
    marginRight: 50,
    marginTop: 10,
  },
  btn:{
    backgroundColor: 'rgb(74,139,204)',
    height:45,
    borderRadius:3,
    //width:width,
    marginLeft:50,
    marginRight:50,
    marginTop:20,
  
  },
  font:{
     color:"#FFF",
     alignSelf: 'center',
  },
  font2:{
    color:"#FFF",
    alignSelf: 'center',
    marginTop: 6,
    fontSize:10
 },
  fengexian:{
    color:'white',
    alignSelf: 'center',
    marginTop: 60,
    fontSize:10,
   
  },
  share:{
   
    flexDirection: 'row',
    marginTop: 20,
    justifyContent: 'space-around',
    //alignContent: 'ce',
  },
  
  qq1:{
   width:"100%",
   height:"100%",
   resizeMode:'contain',
    alignSelf: 'center',
  },
  qq2:{
    width:"100%",
    height:"100%",
    resizeMode:'contain',
    alignSelf: 'center',
   },
  weixin:{
    width:40,
    height:40
  }



});

// const route =createStackNavigator({
//   login:{screen:App},
//   main:{screen:mainPage},
//   register:{screen:registerPage},
//   frogetPass:{screen:forgetPassPage},
//   peel:{screen:peelPage},
//   check:{screen:checkPage},
//   qr:{screen:qrPage},
//   blood:{screen:bloodPage},
//   ovu:{screen:ovuPage},
//   preg:{screen:pregPage},
//   checkPeelResult:{screen:checkPeelResultPage}
  
// },
// {
//   navigationOptions:{ 
//      headerTitleStyle:{color:'white',fontSize:16, top:Platform.OS==='ios'?0:10,flex:1,textAlign: 'center'},
//      headerBackTitleStyle:{color:'white'},
//      headerStyle:{backgroundColor:'rgb(30,70,125)',color:'white',height:50,fontSize:16},
//     //  headerBackTitle:'尿常规检测',
//      headerTintColor:'#fff',
//      headerRight:<View/>,
//   }
// }
// );


function mapStateToProps(state){

        const {Net,Nav}=state;
        return {
              Net,
               Nav
         }

}





export default connect(mapStateToProps)(App);